import axios from "axios";
import { useTokenStore } from "@/stores/token";
import { useUserInfoStore } from "@/stores/userInfo";
import { showFailToast, showLoadingToast } from "vant";
const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();
const baseURL = "/api";
const instance = axios.create({
  baseURL,
  timeout: 10000,
});
let loading = null;
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    loading = showLoadingToast({
      message: "加载中...",
      forbidClick: true,
    });
    // 携带token
    const token = tokenStore.token;
    if (token) {
      config.headers.jwt = token;
    }
    // 在发送请求之前做些什么
    return config;
  },
  (error) => {
    if (loading) {
      loading.close();
    }
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (loading) {
      loading.close();
    }
    // 对响应数据做点什么
    if (response.data.errno === 0) {
      return response.data;
    }
    if (response.data.errno === 2) {
      tokenStore.removeToken();
      userInfoStore.removeUserInfo();
    }
    showFailToast(response.data.errmsg);
    return Promise.reject(response.data);
  },
  (error) => {
    if (loading) {
      loading.close();
    }
    showFailToast("服务器错误，请稍后再试");
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);
export default instance;
